import { defineComponent } from 'vue';
import {
  GridFieldColumnController,
  GridRowState,
  convertNavData,
} from '@ibiz-template/runtime';
import { useNamespace } from '@ibiz-template/vue3-util';
import './column-search.scss';

export const ColumnSearch = defineComponent({
  name: 'ColumnSearch',
  props: {
    controller: {
      type: GridFieldColumnController,
      required: true,
    },
    row: {
      type: GridRowState,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('column-search');
    const { data } = props.row;
    const { context, model } = props.controller;
    const value = data[model.codeName!] || '';
    const search = async (e: Event) => {
      e.stopPropagation();
      e.preventDefault();
      const viewconfig = {
        id: model.linkAppViewId || '',
        fieldName: model.codeName || '',
      };
      const { userParam } = model;
      let _params: IData = {};
      if (userParam) {
        const navparams: IData = {};
        Object.keys(userParam).forEach((_item: string) => {
          if (_item.includes('SRFNAVPARAM') || _item.includes('SRFNAVCTX')) {
            const keys = _item.split('.');
            navparams[keys[1]] = userParam[_item];
          }
        });
        _params = convertNavData(navparams, data, context) || [];
      }
      const res = await ibiz.openView.drawer(viewconfig.id, context, _params);

      if (res && res.ok && res.data) {
        return res.data;
      }
    };
    return {
      data,
      ns,
      value,
      search,
    };
  },
  render() {
    return (
      <div class={this.ns.b()}>
        <div>{this.value}</div>
        <div
          class={this.ns.e('search-btn')}
          onClick={(e: Event) => this.search(e)}
        >
          搜索
        </div>
      </div>
    );
  },
});
